<?php

namespace app\controllers;

use app\models\Admin;
use Yii;
use yii\web\Controller;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ]
        ];
    }

    public function actionIndex()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(['oauth/login']);
        }
        return $this->render('index', [
            'jsParams' => $this->setupJsApi()
        ]);
    }

    public function actionDashboard()
    {
        if (Yii::$app->request->isPost) {
            $username = Yii::$app->request->getBodyParam('username');
            $password = Yii::$app->request->getBodyParam('password');
            $remember = Yii::$app->request->getBodyParam('remember', false);
            $admin = Admin::findIdentityByAccount($username, $password);
            if (empty($admin)) {
                Yii::$app->session->setFlash('error', '账号或密码错误');
            } else {
                Yii::$app->admin->login($admin, $remember ? 7 * 24 * 3600 : 0);
                return $this->redirect(['/admin/default/index']);
            }
        }
        return $this->render('dashboard');
    }

    private function setupJsApi()
    {
        $apis = [
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'closeWindow'
        ];
        return Yii::$app->wechat->getJsApiSign(Yii::$app->urlManager->createAbsoluteUrl(['/']), $apis, YII_ENV_DEV);
    }
}
